package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.MenuMapper;

import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = MenuService.class)
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Map> getMenus(Integer userId) {
        List<Menu> list = menuMapper.findMenuParentList(userId);
        ArrayList<Map> result = new ArrayList<>();
        for (Menu menu : list) {
            Map map = new HashMap<>();
            Integer id = menu.getId();
            List<Menu> l = menuMapper.findMenuChildrenList(userId,id);
            ArrayList<Map> children = new ArrayList<>();
            for (Menu m : l) {
                Map child = new HashMap();
                child.put("path", m.getPath());
                child.put("title", m.getName());
                child.put("linkUrl", m.getLinkUrl());
                child.put("children",m.getChildren());
                children.add(child);
            }
            map.put("path", menu.getPath());
            map.put("title", menu.getName());
            map.put("icon", menu.getIcon());
            map.put("children",children);
            result.add(map);
        }

        return result;
    }


    /*菜单管理中：分页查询菜单*/
    @Override
    public PageResult findMenuByPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);
        List<Menu> list = menuMapper.findMenuByPage(queryString);
        PageInfo<Menu> pageinfo = new PageInfo<>(list);

        return new PageResult(pageinfo.getTotal(),pageinfo.getList());
    }

    @Override
    public void updateMenu(Menu menu) {
        menuMapper.updateMenu(menu);

    }

    @Override
    public void addMenu(Menu menu) {
        menuMapper.addMenu(menu);
    }

    @Override
    public void deleteMenuById(Integer id) {
        //检查当前有没有被引用
        Integer count=menuMapper.findCountById(id);
        if (count>0) {
            throw new RuntimeException("有用户拥有该菜单，不可删除");
        }
        try {
            menuMapper.deleteMenuById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Menu> findAll() {
        return menuMapper.findAll();

    }
}

